<?php
namespace backend\modules\mobo\controllers;

use Yii;
//use backend\modules\mobo\models\BackendMenu;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\base\BaseBackendController;

use \backend\modules\mobo\models\BackendMenu;
use common\components\Tree;

class MenuController extends BaseBackendController
{


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                //'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout', 'index', 'cache', 'create', 'update', 'delete', 'batch', 'display'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }



    public function actionIndex()
    {
		$parentid = 0;
		exit($this->module);
		
		$list = Yii::$app->FileCache ->get('backend_menu');
		$tree = new Tree();
		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        //print_r($list);
		//exit;
		foreach($list as $k=>$r) {
			$list[$k]['str_manage'] = '<a href="'.Yii::$app->urlManager->createUrl(['/mobo/menu/update','menuid'=>$r['menuid']]).'" title="编辑" class="operation-update">编辑</a> <a href="'.Yii::$app->urlManager->createUrl(['/mobo/menu/delete','menuid'=>$r['menuid']]).'" title="删除" class="operation-delete">删除</a>';
			$url = Yii::$app->urlManager->createUrl(['/mobo/menu/display', 'menuid'=>$r['menuid'], 'locked'=> '-locked-']);
			$list[$k]['display_button'] = '<div onclick="change_switch(this, \''.$url.'\');" id="btn-locked" class="locked-'.intval($r['display']).'"></div>';
		}
			
		
				$str  = "<tr>
					<td align='center'><input name='listorders[\$menuid]' type='text' size='3' value='\$listorder' class='input-text input-listorder'></td>
					<td align='center'>\$menuid</td>
					<td >\$spacer\$name</td>
					<td class='td-locked'>\$display_button</td>
					<td align='center'>\$str_manage</td>
				</tr>";
		$tree->init($list);
        $tr = $tree->get_tree(0,$str, $parentid);
		

		return $this->renderPartial('index',array(
                'tr'=>$tr,
		));
  
    }

	//更新文件缓存
	public function actionCache($goback = false){
		set_time_limit(0);
	    $sql = "SELECT * FROM {{%backend_menu}} order by listorder asc,menuid asc";
		$citydata = Yii::$app->db->createCommand($sql)->queryAll();
		$data = array();
		$data_parent = array();
		foreach($citydata as $k=>$v){
			$v['url'] = Yii::$app->urlManager->createUrl($v['controllers']).'/'.$v['params'];
			$v['id'] = $v['menuid'];
			$data[$v['menuid']] = $v;
			
			if ($v['parentid'] == 0 && $v['display']) $data_parent[$v['menuid']] = $v;
		}
		//FileCache::set('backend_menu', $data);
		Yii::$app->FileCache ->set('backend_menu_parent', $data_parent);
		Yii::$app->FileCache ->set('backend_menu', $data);
		if ($goback){
			$this->OperTips(['backurl'=> 'mobo/menu/index']);
		}
	}
	
	
	public function actionCreate(){
		$this->CreateUpdate();
	}
	
	public function actionUpdate($menuid){
		$this->CreateUpdate($menuid);
	}
	
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/city/_form.php
	 */
	public function CreateUpdate($menuid = null)
	{
		$model=self::findModel($menuid);
		if ($model->load(Yii::$app->request->post()))
		{
			if (!$menuid) $model->datetime = time();
			if($model->save()){
				self::actionCache();
			    $this->OperTips(['backurl'=> '/mobo/menu/index']);
			}
		}
		$model->parentid = isset($_GET['parentid']) ? $_GET['parentid'] : 0;
     	echo $this->renderPartial('_form',array(
			'model'=>$model,
			'select'=>$this->SelectOptions($model->parentid)
		));
	}


	/**
	 * 下拉树形
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
    public function SelectOptions($parentid = 0){
		$tree = new Tree();
		$data = Yii::$app->FileCache->get('backend_menu');
		$tree->init($data);
		$str = "<option value='\$menuid'  \$selected>\$spacer\$name</option>\n"; //生成的形式
        $select = $tree->get_tree(0,$str, $parentid);
		return $select;
		
	}

	/**
	 * 删除某一条数据
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionDelete($menuid)
	{
		$sql = "SELECT menuid FROM {{%backend_menu}} where parentid = $menuid";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		if ($data){
			$this->OperTips([
			    'backurl'=> $_SERVER['HTTP_REFERER'],
				'type'=> '',
				'title'=> '删除失败',
				'content'=> '请先删除该分类的下级分类',
				'timeout'=> 5000,
				'error'=>true
			]);

		}
		$this->findModel($menuid)->delete();
        self::actionCache();
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax'])){
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
	}
    
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionBatch()
	{
        $ids = isset($_POST['checked_id']) ? $_POST['checked_id'] : NULL;
		$tips = '';
		$backurl = $_SERVER['HTTP_REFERER'];
        if ($ids){
            if (isset($_POST['batch_delete'])){
                BackendMenu::find()->where(['deleted' => false])->all()->delete();
            }
        }else if(isset($_POST['batch_listorder'])){
			if ($_POST['listorders']) foreach($_POST['listorders'] as $id=>$listorder){
				 BackendMenu::updateAll(array('listorder'=>intval($listorder)), 'menuid='.$id);
			}
		}
        self::actionCache();
		$this->OperTips(['backurl'=> '/mobo/menu/index']);
	}


    /**
     * 启用关闭帖子
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/article/index.php
     */
    public function actionDisplay($menuid, $locked) {
        $sql = "update {{%backend_menu}} set `display` = $locked where menuid = '$menuid'";
        Yii::$app->db->createCommand($sql)->query();
        $this->actionCache();
    }

    public function actionGetdata(){
		$model=self::loadModel();

		$data = $model->getdata($_GET['parentid']);
		echo CJSON::encode($data);
		
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Menu the loaded model
	 * @throws CHttpException
	 */
    protected function findModel($id = '')
    {
		$model =$id ? BackendMenu::findOne($id) : new BackendMenu;
        if ( $model !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
